import { Node, Vec3 } from 'cc';
import { ViewUtil } from 'db://app-game/core/utils/ViewUtil';
import { BTTreeComp } from 'db://app-game/libs/ecs/common/bll/BTTreeSystem';
import { ecs } from 'db://app-game/libs/ecs/ECS';
import { BehaviorManager } from 'db://app-game/libs/math/behavior-tree/BehaviorManager';
import MonsterBTTree from '../../../bt-tree/tree/MonsterBTTree';
import { Lineup } from '../../biz/level-map/LevelMap.type';
import { smc } from '../../singleton/SingletonModuleComp';
import { MonitorModelAttackComp } from './model/MonitorModelAttackComp';
import { MonitorModelComp } from './model/MonitorModelComp';
import { MonsterModelComp } from './model/MonsterModelComp';
import { MonsterViewComp } from './view/MonsterViewComp';

/** 怪兽 */
@ecs.register('Monster')
export class Monster extends ecs.Entity {
  // 数据层
  MonsterModel!: MonsterModelComp;

  // 业务层
  MonitorModel!: MonitorModelComp; // 监视范围
  MonitorModelAttack!: MonitorModelAttackComp; // 锁定攻击目标
  BTTree!: BTTreeComp; // 行为树

  // 视图层
  MonsterView!: MonsterViewComp;
  init() {
    this.addComponents(MonsterModelComp);
  }

  /** 加载怪兽显示 */
  load(parent: Node, pos: Vec3, lineup: Lineup) {
    // 1.创建预制件
    const node = ViewUtil.createPrefabNode(this.MonsterModel.prefabPath);
    const mv = node.addComponent(MonsterViewComp);
    this.add(mv);

    // 2.设置父节点和位置
    node.setParent(parent);
    node.setPosition(pos);

    // 3.设置阵容
    this.MonsterModel.lineup = lineup;
    this.MonsterModel.enemyLineup = lineup === Lineup.Player ? Lineup.AI : Lineup.Player;
  }

  /** 添加监视组件 */
  addMonitorModel(monitorNodeName: string) {
    this.add(MonitorModelComp);
    this.MonitorModel.node = this.MonsterView.node;
    this.MonitorModel.monitorNodeName = monitorNodeName;
    this.MonitorModel.monitorRange = this.MonsterModel.monitorRange;
    this.MonitorModel.getColliderList = smc.level.LevelMap.colliderList;
  }

  /** 锁定攻击目标 */
  lockAttackTarget(target: Node) {
    this.add(MonitorModelAttackComp);
    this.MonitorModelAttack.attackRange = this.MonsterModel.attackRange;
    this.MonitorModelAttack.lockTarget = target;
  }

  /** 添加行为树组件 */
  addBTTree() {
    this.add(BTTreeComp);
    this.BTTree.tree = new MonsterBTTree();
    this.BTTree.behaviorManager = new BehaviorManager(this, this.BTTree.tree);
    this.BTTree.behaviorManager.start();
  }

  /** 攻击 */
  attack() {
    return true;
  }
}
